package org.jeecg.api.Interceptor;

import org.jeecg.api.annotation.ApiNeedLogin;
import org.jeecg.api.utils.MiniappSpringContextUtils;
import org.jeecg.common.exception.AuthException;
import org.jeecg.common.system.util.JwtTokenUtil;
import org.jeecg.common.system.util.SignDO;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhongchao
 * @tile TokenInterceptor
 * @date 2020-05-12
 * @since v1.0.0
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            ApiNeedLogin annotation = AnnotationUtils.findAnnotation(handlerMethod.getBean().getClass(), ApiNeedLogin.class);
            annotation = annotation == null ? handlerMethod.getMethodAnnotation(ApiNeedLogin.class) : annotation;
            if (annotation == null) {//不需要验证登录
                return true;
            }
            String token = request.getHeader("app_token");
            if (token == null) {// token为空直接报错
                throw new AuthException(request.getRequestURI());
            }
            SignDO signDO = MiniappSpringContextUtils.getSignDO();
            if (signDO != null) {//session存在用户信息 验证通过
                return true;
            }
            signDO = JwtTokenUtil.unsign(token);
            MiniappSpringContextUtils.setSignDO(signDO);
        }
        return true;
    }
}
